# gui/stats_tab.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from datetime import datetime
from stats import StatsAnalyzer


class StatsTab:
    """Stats page: weekly table + contribution-style heatmap."""

    def __init__(self, parent) -> None:
        self.parent = parent
        self.frame = ttk.Frame(self.parent)

        main_frame = ttk.Frame(self.frame)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)

        weekly_frame = ttk.LabelFrame(main_frame, text="周统计")
        weekly_frame.pack(fill=tk.X, pady=15)

        self.weekly_tree = ttk.Treeview(
            weekly_frame, columns=("week", "duration"), show="headings", height=6
        )
        self.weekly_tree.heading("week", text="周")
        self.weekly_tree.heading("duration", text="总时长")
        self.weekly_tree.column("week", width=260)
        self.weekly_tree.column("duration", width=120, anchor=tk.CENTER)
        self.weekly_tree.pack(fill=tk.X)

        heatmap_frame = ttk.LabelFrame(main_frame, text="近半年热力图")
        heatmap_frame.pack(fill=tk.BOTH, expand=True, pady=15)

        self.canvas = tk.Canvas(heatmap_frame, bg="white", width=300, height=200)
        scroll_x = ttk.Scrollbar(
            heatmap_frame, orient="horizontal", command=self.canvas.xview
        )
        scroll_y = ttk.Scrollbar(
            heatmap_frame, orient="vertical", command=self.canvas.yview
        )
        self.canvas.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)

        heatmap_frame.columnconfigure(0, weight=1)
        heatmap_frame.rowconfigure(0, weight=1)

        self.canvas.grid(row=0, column=0, sticky="nsew")
        scroll_y.grid(row=0, column=1, sticky="ns")
        scroll_x.grid(row=1, column=0, sticky="ew")

        # Initial render
        self.refresh()

    # Public API called by MainWindow when data changes
    def refresh(self) -> None:
        analyzer = StatsAnalyzer()

        # Weekly table
        for item in self.weekly_tree.get_children():
            self.weekly_tree.delete(item)
        for week, total in analyzer.get_weekly_stats().items():
            self.weekly_tree.insert(
                "", "end", values=(week, analyzer.format_duration(total))
            )

        # Heatmap
        self.canvas.delete("all")
        color_data = analyzer.get_color_mapping()
        duration_data = analyzer.get_duration_data()

        dates = sorted(duration_data.keys())
        if not dates:
            return

        start_date = min(dates)
        end_date = max(dates)
        current_date = start_date
        col, row = 0, 0
        month_labels = []

        cell_size = 15
        margin = 2

        while current_date <= end_date:
            if current_date.day == 1:
                month_labels.append((current_date.strftime("%m月"), col))
            color = color_data.get(current_date, "#ebedf0")
            x1 = col * (cell_size + margin)
            y1 = row * (cell_size + margin)
            x2 = x1 + cell_size
            y2 = y1 + cell_size
            self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="")

            # Next day
            if current_date.weekday() == 6:  # Sunday -> new column
                col += 1
                row = 0
            else:
                row += 1
            current_date += (
                analyzer.timedelta(days=1)
                if hasattr(analyzer, "timedelta")
                else __import__("datetime").timedelta(days=1)
            )

        # Month labels
        for label, c in month_labels:
            self.canvas.create_text(
                c * (cell_size + margin), -10, anchor="w", text=label
            )

        # Resize scroll region
        width = (col + 1) * (cell_size + margin)
        height = 7 * (cell_size + margin)
        self.canvas.config(scrollregion=(0, -20, width, height))
